package com.sinodata.bsm.cicp.collector.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CommandReader;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description:计算秒流量的正则匹配Shell采集器，使用正则表达式匹配两次采集的结果，求每秒的流量。
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-20 15:29:33      liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class FlowRegexMatchShellCollector extends Collector {

    private static final Logger logger = Logger.getLogger(FlowRegexMatchShellCollector.class);

    private double[] lastValue = null;

    private long lastTime = -1;

    /**
     * 默认构造方法
     */
    public FlowRegexMatchShellCollector() {

    }

    /**
     * 采集方法
     * @throws CollectorException
     */
    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String cmd = this.paramMap.get("collectCmd");
        String regex = this.paramMap.get("Regex");
        Pattern pattern = Pattern.compile(regex);
        BufferedReader reader = null;
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        String[] propMetas = getPropMeta();
        try {
            reader = CommandReader.getReader(ip, cmd, (int) this.interval, 0);
            String readLine = null;
            double[] tmpValues = new double[propMetas.length];
            boolean matched = false;
            while ((readLine = reader.readLine()) != null) {
                Matcher matcher = pattern.matcher(readLine);
                if (matcher.find()) {
                    for (int i = 0; i < tmpValues.length; i++) {
                        tmpValues[i] = Double.parseDouble(matcher.group(i + 1));
                    }
                    matched = true;
                    break;
                }
            }
            if (matched) {
                long currentTimeMillis = System.currentTimeMillis();
                if (lastTime > 0 && lastValue != null && lastValue.length == tmpValues.length && currentTimeMillis > lastTime) {
                    ResPropertyValue propertyValueX = new ResPropertyValue();
                    ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[tmpValues.length];
                    for (int i = 0; i < propValues.length; i++) {
                        double v = ((tmpValues[i] - lastValue[i]) / (currentTimeMillis - lastTime)) * 1000;
                        v = ((long) (v * 10d)) / 10d;
                        propValues[i] = ResPropertyValue.createPropValue(String.valueOf(v), propMetas[i]);
                    }
                    propertyValueX.setValues(propValues);
                    values.add(propertyValueX);
                }
                lastTime = currentTimeMillis;
                lastValue = tmpValues;
            }
        } catch (Exception e) {
            logger.error("when excute FlowRegexMatchShellCollector error occured", e);
            throw new CollectorException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("when closed reader error occured", e);
                }
            }
        }
        return values;
    }

    @Override
    public String[] getParamMeta() {
        //return new String[] { "collectCmd", "Regex", "matchNum" };
        return new String[] { "collectCmd", "Regex" };
    }

    @Override
    public String[] getPropMeta() {
        // int count = Integer.parseInt(this.paramMap.get("matchNum"));
        Pattern pattern = Pattern.compile(this.paramMap.get("Regex"));
        Matcher matcher = pattern.matcher("");
        int count = matcher.groupCount();
        String[] propMetas = new String[count];
        for (int i = 1; i <= propMetas.length; i++) {
            propMetas[i - 1] = "$" + i;
        }
        return propMetas;
    }

    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {

    }

}
